<?php

namespace App\Modules\User;

use App\Modules\Order\Models\Order;
use App\Modules\Order\Models\RewardRecord;
use App\Modules\User\Models\Account;
use App\Modules\User\Models\Member;
use App\Modules\User\Models\User;
use App\Modules\User\Models\WeChatCompanyPay;
use App\Modules\User\Models\Withdrawal;
use Carbon\Carbon;
use Illuminate\Console\Scheduling\Schedule as BaseSchedule;
use Illuminate\Support\Facades\Log;

class Schedule
{
    public static function invoke(BaseSchedule $schedule)
    {
//        $schedule->call([self::class, 'checkCompanyPay'])->everyFiveMinutes()->name('校验企业付款');
//        $schedule->call([self::class, 'checkWithdrawal'])->everyMinute()->name('校验提现');
        $schedule->call([self::class, 'checkMember'])->twiceDaily(1, 18)->name('检查会员等级');
        $schedule->call([self::class, 'refreshRank'])->hourly()->name('刷新排行榜');
    }

    public static function refreshRank()
    {
        ShareRank::refresh();
        UnlockRank::refresh();
        VisitorRank::refresh();
    }

    public static function checkMember()
    {
        User::query()
            ->where('level', 1)
            ->orderBy('id', 'desc')
            ->each(function ($item) {
                $member = Member::query()
                    ->where('user_id', $item->id)
                    ->selectRaw('sum(quota) as all_quota, sum(rebate) as all_rebate')
                    ->first();
                if ($member->all_quota - $member->all_rebate <=0 ) {
                    $item->level = 0;
                    $item->save();
                }
            });
    }

//    public static function checkWithdrawal()
//    {
//        Withdrawal\::query()
//            ->where('status', Withdrawal::STATUS_INIT)
//            ->lockForUpdate()
//            ->each(function (Withdrawal $item) {
//                $tmp = WeChatCompanyPay::query()
//                    ->find($item->link_id);
//                if ($tmp->status == 'FAIL') {
//                    $item->fail();
//                } elseif($tmp->status == "SUCCESS") {
//                    $item->success();
//                }
//            });
//    }

//    public static function checkCompanyPay()
//    {
//        WeChatCompanyPay::query()
//            ->where('status', WeChatCompanyPay::STATUS_SENDING)
//            ->each(function (WeChatCompanyPay $item) {
//                $item->checkStatus();
//            });
//        return ;
//    }
}
